package com.changeover.gwt.login.server;

import java.text.MessageFormat;

import org.springframework.stereotype.Service;

import com.changeover.gwt.login.client.ILoginService;
import com.changeover.gwt.login.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@Service("loginService")
public class LoginService implements ILoginService {

    public String login(String login, String password) throws IllegalArgumentException {
        // Escape data from the client to avoid cross-site script vulnerabilities.
        login = escapeHtml(login);
        password = escapeHtml(password);

        // Verify that the input is valid.
        if (!FieldVerifier.isValidLogin(login)) {
            // If the input is not valid, throw an IllegalArgumentException back to
            // the client.
            throw new IllegalArgumentException("Name must be at least 4 characters long");
        }

        if (!FieldVerifier.isValidPassword(password)) {
            // If the input is not valid, throw an IllegalArgumentException back to
            // the client.
            throw new IllegalArgumentException("Name must be at least 6 characters long");
        }

        return MessageFormat.format("Hello ''{0}'' with password ''{1}'' in The Change Over.", login, password);
    }

    /**
     * Escape an html string. Escaping data received from the client helps to prevent cross-site
     * script vulnerabilities.
     * 
     * @param html
     *            the html string to escape
     * @return the escaped string
     */
    private String escapeHtml(String html) {
        if (html == null) {
            return null;
        }
        return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    }
}
